package com.example.demo.service.Impl;

import com.example.demo.ao.CensusDataAo;
import com.example.demo.mapper.MoreImageMapper;
import com.example.demo.service.CensusDataSpeedService;
import com.example.demo.utils.ImageMergeUtil;
import com.example.demo.vo.BlobImageBase64;
import com.example.demo.vo.CensusDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

@Service
public class CensusDataSpeedServiceImpl implements CensusDataSpeedService {


    @Autowired
    private MoreImageMapper moreImageMapper;


    // 创建专用线程池处理图片（核心优化点）
    private final ExecutorService imageProcessingExecutor = Executors.newFixedThreadPool(
            Math.max(4, 10), // 根据CPU核心数动态调整
            new ThreadFactory() {
                private final AtomicInteger threadCount = new AtomicInteger(0);

                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName("image-processor-" + threadCount.incrementAndGet());
                    thread.setDaemon(true); // 设置为守护线程
                    return thread;
                }
            }
    );

    @Override
    public List<CensusDataVo> censusDataSpeed(CensusDataAo censusDataAo) {
        // 1. 获取所有普查数据（单次数据库查询）
        List<CensusDataVo> dataList = moreImageMapper.censusData(censusDataAo);
        if (dataList.isEmpty()){
            return dataList;
        }

        // 2. 收集所有图片ID（不去重）
        List<Integer> allImageIds = collectAllImageIds(dataList);

        // 3. 批量查询所有图片Base64数据（单次数据库查询）
        Map<Integer, String> imageBase64Map = getImageBase64Map(allImageIds);

        // 4. 并行处理每条记录（核心优化点）
        processRecordsInParallel(dataList, imageBase64Map);

        return dataList;
    }

    // 高效收集所有图片ID
    private List<Integer> collectAllImageIds(List<CensusDataVo> dataList) {
        // 预分配空间（假设每条记录平均20个图片ID）
        List<Integer> allImageIds = new ArrayList<>(dataList.size() * 20);

        for (CensusDataVo vo : dataList) {
            addImageIds(allImageIds, vo.getLocationImg());
            addImageIds(allImageIds, vo.getDeviceTypeImg());
            addImageIds(allImageIds, vo.getManuImg());
            addImageIds(allImageIds, vo.getInstantaneousImg());
            addImageIds(allImageIds, vo.getOvercurrentImg());
            addImageIds(allImageIds, vo.getLimitedImg());
            addImageIds(allImageIds, vo.getZeroSeqImg());
            addImageIds(allImageIds, vo.getPostAccFixedCurImg());
            addImageIds(allImageIds, vo.getPostAccFixedTimeImg());
            addImageIds(allImageIds, vo.getCabinetProImg());
            addImageIds(allImageIds, vo.getProtectionImg());
            addImageIds(allImageIds, vo.getVoManuImage());
            addImageIds(allImageIds, vo.getVoInstantaneousImage());
            addImageIds(allImageIds, vo.getVoOvercurrentImage());
            addImageIds(allImageIds, vo.getVoLimited());
            addImageIds(allImageIds, vo.getVoZeroSeqImage());
            addImageIds(allImageIds, vo.getVoRearAccelerationImage());
            addImageIds(allImageIds, vo.getVoRearAccelerationTimeImage());
            addImageIds(allImageIds, vo.getBasImage());
            addImageIds(allImageIds, vo.getParentImage());
            addImageIds(allImageIds, vo.getLineInOneImage());
            addImageIds(allImageIds, vo.getLineInTwoImage());
        }
        return allImageIds;
    }

    // 批量获取图片数据
    private Map<Integer, String> getImageBase64Map(List<Integer> allImageIds) {
        if (allImageIds.isEmpty()) return Collections.emptyMap();

        List<BlobImageBase64> base64List = moreImageMapper.getBase64ImagesByIds(allImageIds);
        Map<Integer, String> imageBase64Map = new HashMap<>(base64List.size());

        for (BlobImageBase64 item : base64List) {
            String cleanedBase64 = cleanBase64(item.getImageBase64());
            imageBase64Map.put(item.getId(), cleanedBase64);
        }
        return imageBase64Map;
    }

    // 并行处理所有记录（核心优化点）
    private void processRecordsInParallel(List<CensusDataVo> dataList, Map<Integer, String> imageBase64Map) {
        // 使用CountDownLatch跟踪任务完成
        CountDownLatch latch = new CountDownLatch(dataList.size());

        for (CensusDataVo vo : dataList) {
            imageProcessingExecutor.submit(() -> {
                try {
                    processSingleRecord(vo, imageBase64Map);
                } finally {
                    latch.countDown();
                }
            });
        }

        // 等待所有任务完成（设置超时时间）
        try {
            latch.await(5, TimeUnit.MINUTES); // 5分钟超时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // 处理单条记录的所有图片
    private void processSingleRecord(CensusDataVo vo, Map<Integer, String> imageBase64Map) {
        // 位置图片
        processImageField(vo.getLocationImg(), imageBase64Map,
                vo::setLocationImageList, vo::setLocationImageData);

        // 分界点图片
        processImageField(vo.getDeviceTypeImg(), imageBase64Map,
                vo::setDeviceTypeImageList, vo::setDeviceTypeImageData);

        // 装置图片
        processImageField(vo.getManuImg(), imageBase64Map,
                vo::setManuImageList, vo::setManuImageData);

        // 速断图片
        processImageField(vo.getInstantaneousImg(), imageBase64Map,
                vo::setInstantaneousImageList, vo::setInstantaneousImageData);

        // 过流图片
        processImageField(vo.getOvercurrentImg(), imageBase64Map,
                vo::setOvercurrentImageList, vo::setOvercurrentImageData);

        // 限时速断图片
        processImageField(vo.getLimitedImg(), imageBase64Map,
                vo::setLimitedImageList, vo::setLimitedImageData);

        // 零序图片
        processImageField(vo.getZeroSeqImg(), imageBase64Map,
                vo::setZeroSeqImageList, vo::setZeroSeqImageData);

        // 后加速电流图片
        processImageField(vo.getPostAccFixedCurImg(), imageBase64Map,
                vo::setPostAccFixedCurImageList, vo::setPostAccFixedCurImageData);

        // 后加速时间图片
        processImageField(vo.getPostAccFixedTimeImg(), imageBase64Map,
                vo::setPostAccFixedTimeImageList, vo::setPostAccFixedTimeImageData);

        // 进线柜图片
        processImageField(vo.getCabinetProImg(), imageBase64Map,
                vo::setCabinetProImageList, vo::setCabinetProImageData);

        // 保护图片
        processImageField(vo.getProtectionImg(), imageBase64Map,
                vo::setProtectionImageList, vo::setProtectionImageData);

        // 装置图片 (高压)
        processImageField(vo.getVoManuImage(), imageBase64Map,
                vo::setVoManuImageList, vo::setVoManuImageData);

        // 速断图片 (高压)
        processImageField(vo.getVoInstantaneousImage(), imageBase64Map,
                vo::setVoInstantaneousImageList, vo::setVoInstantaneousImageData);

        // 过流图片 (高压)
        processImageField(vo.getVoOvercurrentImage(), imageBase64Map,
                vo::setVoOvercurrentImageList, vo::setVoOvercurrentImageData);

        // 限时速断图片 (高压)
        processImageField(vo.getVoLimited(), imageBase64Map,
                vo::setVoLimitedImageList, vo::setVoLimitedImageData);

        // 零序图片 (高压)
        processImageField(vo.getVoZeroSeqImage(), imageBase64Map,
                vo::setVoZeroSeqImageList, vo::setVoZeroSeqImageData);

        // 后加速图片 (高压)
        processImageField(vo.getVoRearAccelerationImage(), imageBase64Map,
                vo::setVoRearAccelerationImageList, vo::setVoRearAccelerationImageData);

        // 后加速时间图片 (高压)
        processImageField(vo.getVoRearAccelerationTimeImage(), imageBase64Map,
                vo::setVoRearAccelerationTimeImageList, vo::setVoRearAccelerationTimeImageData);

        // 备自投装置图片
        processImageField(vo.getBasImage(), imageBase64Map,
                vo::setBasImageList, vo::setBasImageData);

        // 母联图片
        processImageField(vo.getParentImage(), imageBase64Map,
                vo::setParentImageList, vo::setParentImageData);

        // 进线1图片
        processImageField(vo.getLineInOneImage(), imageBase64Map,
                vo::setLineInOneImageList, vo::setLineInOneImageData);

        // 进线2图片
        processImageField(vo.getLineInTwoImage(), imageBase64Map,
                vo::setLineInTwoImageList, vo::setLineInTwoImageData);
    }

    // 辅助方法：添加图片ID到集合
    private void addImageIds(List<Integer> allImageIds, String imgIds) {
        if (imgIds != null && !imgIds.isEmpty()) {
            String[] ids = imgIds.split(",");
            for (String id : ids) {
                try {
                    allImageIds.add(Integer.parseInt(id.trim()));
                } catch (NumberFormatException e) {
                    // 忽略无效ID
                }
            }
        }
    }

    // 优化后的图片处理方法（单图不合并）
    private void processImageField(String imgIds, Map<Integer, String> imageBase64Map,
                                   Consumer<List<String>> setImageList, Consumer<byte[]> setImageData) {
        if (imgIds == null || imgIds.isEmpty()) {
            return;
        }

        List<String> base64List = new ArrayList<>();
        String[] ids = imgIds.split(",");
        for (String idStr : ids) {
            try {
                int id = Integer.parseInt(idStr.trim());
                String base64 = imageBase64Map.get(id);
                if (base64 != null) {
                    base64List.add(base64);
                }
            } catch (NumberFormatException e) {
                // 忽略无效ID
            }
        }

        // 设置到List字段
        setImageList.accept(base64List);

        // 优化：单张图片不合并
        if (base64List.isEmpty()) return;

        if (base64List.size() == 1) {
            // 单张图片直接使用
            try {
                byte[] imageData = Base64.getDecoder().decode(base64List.get(0));
                setImageData.accept(imageData);
            } catch (IllegalArgumentException e) {
                setImageData.accept(null);
            }
        } else {
            // 多张图片才合并
            try {
                byte[] mergedImage = ImageMergeUtil.mergeImages(base64List);
                setImageData.accept(mergedImage);
            } catch (Exception e) {
                setImageData.accept(null);
            }
        }
    }

    // 清理Base64数据
    private String cleanBase64(String base64) {
        if (base64 == null) return null;

        // 移除数据URI前缀
        if (base64.startsWith("data:image")) {
            int commaIndex = base64.indexOf(',');
            if (commaIndex > 0) {
                base64 = base64.substring(commaIndex + 1);
            }
        }
        // 移除换行符和空格
        return base64.replaceAll("\\s", "");
    }
}
